package com.softa.service.thread;

import com.softa.dao.dto.OrderDTO;
import com.softa.dao.mapper.base.SysFileMapper;
import com.softa.dao.model.SysFile;
import com.softa.ftp.Ftp;
import com.softa.ftp.FtpUtil;
import com.softa.service.system.SysMessageService;
import com.softa.utils.CommonUtil;
import com.softa.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * Created by yangl on 2017/8/26.
 */
public class UploadFtpThread implements Runnable {

    /**本地异常日志记录对象  */
    protected static  final Logger logger = LoggerFactory.getLogger(UploadFtpThread.class);

    private SysMessageService sysMessageService;

    private SysFileMapper sysFileMapper;

    private RedisTemplate<Object, Object> redisTemplate;

    private OrderDTO orderDTO;

    public UploadFtpThread(SysMessageService sysMessageService,
                          OrderDTO orderDTO,
                          RedisTemplate<Object, Object> redisTemplate,
                          SysFileMapper sysFileMapper) {
        this.sysMessageService = sysMessageService;
        this.orderDTO = orderDTO;
        this.redisTemplate = redisTemplate;
        this.sysFileMapper = sysFileMapper;
    }
    @Override
    public void run() {
        String filepath = CommonUtil.getPath();
        List<Long> pics = orderDTO.getPics();
        if(CollectionUtils.isNotEmpty(pics)){
            for(Long id : pics){
                uploadftp(id, filepath);
            }
        }
    }

    public void uploadftp(Long id, String filepath){
        String fileDocName = null;
        String fileName = null;
        SysFile sysFile = sysFileMapper.selectByPrimaryKey(id);
        if(null != sysFile){
            fileDocName = sysFile.getDocName();
            fileName = sysFile.getPath();
            filepath = filepath+"/"+sysFile.getFileType()+"/"+sysFile.getPath();
            /**
             * TODO ftp信息，后期考虑多个ftp，会配置在数据库里，固先写死
             */
            Ftp f = new Ftp();
            f.setIpAddr("192.168.101.137");
            f.setPort(21);
            f.setUserName("ftpuser");
            f.setPwd("123456");
            f.setPath("/var/www/html");
            logger.info("文件路劲：{}",filepath);
            //上传
            FtpUtil.uploadFileFromProduction(f, fileName, filepath);
            //保存消息记录
            sysMessageService.saveMessage(orderDTO.getPurId(), getMessageContent(fileDocName));
        }
    }

    /**
     * 获取消息模板内容
     * @return
     */
    public String getMessageContent(String fileDocName){
        StringBuilder sb = new StringBuilder();
        sb.append("您的产品【");
        sb.append("产品名称");
        sb.append("】");
        sb.append("【"+fileDocName+"】");
        sb.append("已上传成功，提交时间：");
        sb.append(DateUtils.formatDate());
        return sb.toString();
    }
}
